package com.piece.core.framework.util.schedule;

import com.piece.core.framework.util.string.StringUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.Iterator;
import java.util.Map;

/**
 * 定时任务工厂
 */
@Slf4j
public class ScheduleFactory {

    private Map<String, ScheduleService> scheduleServiceMap;
    private ScheduleService defaultSchedule = null;

    public ScheduleFactory(Map<String, ScheduleService> scheduleServiceMap) {
        log.info("加载 ScheduleFactory ...");
        this.scheduleServiceMap = scheduleServiceMap;
        this.initSchedule();
    }

    private void initSchedule() {
        if (null != this.scheduleServiceMap) {
            Iterator<Map.Entry<String, ScheduleService>> it = scheduleServiceMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, ScheduleService> entry = it.next();
                log.info("加载 ScheduleFactory --> {}", entry.getKey());
                if (null == this.defaultSchedule) {
                    this.defaultSchedule = entry.getValue();
                }
            }
        }
    }

    public void addScheduleHook(String name, ScheduleService schedule) {
        this.scheduleServiceMap.put(name, schedule);
    }

    public ScheduleService get() {
        return this.defaultSchedule;
    }

    public ScheduleService get(String schedule) {
        if (StringUtil.isEmpty(schedule)) return get();
        return this.scheduleServiceMap.get(schedule);
    }
}
